
export default class DateUtils {

    private static instance: DateUtils;
    public static getInstance() {
        if (!this.instance) {
            this.instance = new DateUtils();
        }
        return this.instance;
    }

    private DateUtils() {

    }
    /**
     * 转指定字符串格式
     * @param value
     * @param format 
     */
    public toStr(value: string | number | Date, format: string) {
        const days = ['日', '一', '二', '三', '四', '五', '六'];
        if (typeof value === 'number' && value && value.toString().length < 13) {
            value = Number(value.toString().concat('000'));
        }
        if (typeof value === 'string') {
            value = value.replace(/-/g, '/');
        }
        const date = new Date(value);
        const matches: { [key: string]: string | number } = {
            yyyy: date.getFullYear(),
            mm: this.fill(date.getMonth() + 1),
            dd: this.fill(date.getDate()),
            hh: this.fill(date.getHours()),
            ii: this.fill(date.getMinutes()),
            ss: this.fill(date.getSeconds()),
            m: date.getMonth() + 1,
            d: date.getDate(),
            h: date.getHours(),
            i: date.getMinutes(),
            s: date.getSeconds(),
            w: days[date.getDay()]
        }
        const str = format.replace(/\[([^\]]+)]|y{4}|m{1,2}|d{1,2}|h{1,2}|i{1,2}|s{1,2}|w/g, (match, $1) => {
            return matches[match] as string || match;
        });
        return str;

    }
    /**
     * 转时间戳-单位:毫秒
     * @param value 
     */
    public toMilliseconds(value: string | number | Date) {
        if (typeof value === 'number' && value && value.toString().length < 13) {
            value = Number(value.toString().concat('000'));
        }

        if (typeof value === 'string') {
            value = value.replace(/-/g, '/');
        }
        const date = new Date(value);
        return date.getTime();
    }

    /**
     * 转时间戳-单位: 秒
     */
    public toSeconds(value: string | number | Date) {
        return Math.floor(this.toMilliseconds(value));
    }

    private fill(n: number) {
        return n < 10 ? '0' + n : n;
    }
}

